package my.edu.utils;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

// RSA工具类
public class RSAUtils {
    public static KeyPair genKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        keyPairGen.initialize(1024);
        return keyPairGen.generateKeyPair();
    }


    /**
     * 使用私钥解密数据
     * @param encryptedText 加密后的Base64字符串
     * @param privateKeyStr 私钥字符（从Redis获取）
     * @return 解密后的原始字符串
     */
    public static String decrypt(String encryptedText, String privateKeyStr) throws Exception {
        // 将Base64字符串转换为字节数组
        byte[] encryptedDataBytes = Base64.getDecoder().decode(encryptedText);
        byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyStr);
        // 重构私钥对象
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

        // 解密操作
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(encryptedDataBytes);

        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }
}
